/**
 * Time formatting utility that converts timestamps to readable formats
 * based on the time difference between now and the target time
 * 
 * @param {Date|number|string} timestamp - Target timestamp (Date object, timestamp in ms, or date string)
 * @returns {string} Formatted time string according to rules
 */
export function formatRelativeTime(timestamp) {
  // Convert input to Date object
  const targetTime = timestamp instanceof Date ? timestamp : new Date(timestamp);
  const now = new Date();
  
  // Calculate time difference in milliseconds
  const diffMs = now - targetTime;
  
  // Convert to different time units
  const diffSeconds = Math.floor(diffMs / 1000);
  const diffMinutes = Math.floor(diffSeconds / 60);
  const diffHours = Math.floor(diffMinutes / 60);
  const diffDays = Math.floor(diffHours / 24);
  const diffMonths = Math.floor(diffDays / 30);
  const diffYears = Math.floor(diffDays / 365);
  
  // Format according to rules
  if (diffMinutes < 1) {
    // Less than 1 minute
    return '刚刚';
  } else if (diffHours < 1) {
    // Less than 1 hour
    return `${diffMinutes}分钟前`;
  } else if (diffDays < 1) {
    // Less than 24 hours
    return `${diffHours}小时前`;
  } else if (diffDays < 2) {
    // Less than 48 hours
    const hours = targetTime.getHours().toString().padStart(2, '0');
    const minutes = targetTime.getMinutes().toString().padStart(2, '0');
    return `昨天 ${hours}:${minutes}`;
  } else if (diffYears < 1) {
    // Less than a year
    const month = (targetTime.getMonth() + 1).toString().padStart(2, '0');
    const day = targetTime.getDate().toString().padStart(2, '0');
    const hours = targetTime.getHours().toString().padStart(2, '0');
    const minutes = targetTime.getMinutes().toString().padStart(2, '0');
    return `${month}月${day}日 ${hours}:${minutes}`;
  } else {
    // More than a year
    const year = targetTime.getFullYear();
    const month = (targetTime.getMonth() + 1).toString().padStart(2, '0');
    const day = targetTime.getDate().toString().padStart(2, '0');
    return `${year}年${month}月${day}日`;
  }
}

// Example usage:
// const now = new Date();

// 刚刚 (just now)
// console.log(formatRelativeTime(new Date(now - 30 * 1000))); // 30 seconds ago

// xx分钟前 (xx minutes ago)
// console.log(formatRelativeTime(new Date(now - 10 * 60 * 1000))); // 10 minutes ago

// xx小时前 (xx hours ago)
// console.log(formatRelativeTime(new Date(now - 5 * 60 * 60 * 1000))); // 5 hours ago

// 昨天 xx:xx (yesterday xx:xx)
// console.log(formatRelativeTime(new Date(now - 25 * 60 * 60 * 1000))); // 25 hours ago

// xx月xx日 xx:xx (mm/dd hh:mm)
// console.log(formatRelativeTime(new Date(now - 5 * 24 * 60 * 60 * 1000))); // 5 days ago

// xxxx年xx月xx日 (yyyy/mm/dd)
// console.log(formatRelativeTime(new Date(now - 400 * 24 * 60 * 60 * 1000))); // 400 days ago
